/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import hibernate.AlbumDAO;
import hibernate.ImageDAO;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import photogallery.Image;

/**
 *
 * @author Trungnm
 */
public class UploadFile extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            doUploadFile(request, response);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    public void doUploadFile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        String contentType = request.getContentType();
//        String albumID = request.getParameter("albumid");
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
            try {
                DataInputStream in = new DataInputStream(request.getInputStream());
                int formDataLength = request.getContentLength();
                byte[] dataBytes = new byte[formDataLength];

                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                /* FileItem */
                List /* FileItem */ items = upload.parseRequest(request);

                String albumId = "";
                String caption = "";
                String fileName = "";
                boolean isCover = false;
                String realPath = getServletContext().getRealPath("/");
                for (int i = 0; i < items.size(); i++) {
                    FileItem item = (FileItem) items.get(i);
                    // Process a regular form field
                    if (item.isFormField()) {
                        if ("txtCaption".equals(item.getFieldName())) {
                            caption = item.getString();
                        }
                        if ("albumId".equals(item.getFieldName())) {
                            albumId = item.getString();
                        }
                        if ("isCover".equals(item.getFieldName())) {
                            isCover = true;
                        }
                    } else {                     

                        // Get the uploaded file parameters
                        String fieldName = item.getFieldName();
                        String filePath = item.getName();                

                        if (filePath.lastIndexOf("\\") >= 0) {
                            fileName = filePath.substring(filePath.lastIndexOf("\\"));
                        } else {
                            fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
                        }

                        DefaultFileRenamePolicy rPolicy = new DefaultFileRenamePolicy();
                        File file = new File(realPath + "images\\" + fileName);
                        file = rPolicy.rename(file);
                        fileName = file.getName();
                        item.write(file);
                    }
                }
                ImageDAO imgDao = new ImageDAO();
                Image img = imgDao.insertImage(albumId, "", null, caption, "images/" + fileName, isCover, realPath + "WEB-INF\\");
                
                String url = "DefaultController?action=view_album&albumId=" + albumId;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } catch (Exception ex) {
                Logger.getLogger(UploadFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
